package cn.security.auth.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class CustomUserDetailServiceImpl implements UserDetailsService {
    @Value("${custom.security.default.account}")
    private String defaultAccount;

    @Value("${custom.security.default.password}")
    private String defaultPassword;

    @Autowired
    @Lazy
    private PasswordEncoder passwordEncoder;
    /**
     * swagger
     * @param account
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String account) throws UsernameNotFoundException {
        // todo:从数据库根据账号获取用户信息 主要信息【账号、密码】
        if (!account.equals(defaultAccount)){
            throw new UsernameNotFoundException("用户不存在");
        }
        // 模拟用户信息
        //User user = new User();
        //user.setAccount(account);
        // 默认的话{noop}123 表示明文密码，告诉spring match比对明文
        account = defaultAccount;
        // todo:此处若加密过的，就用加密过的密码无需encode，之后springSecurity的会自动比对加密后的密码，成功会登录成功
        User user;
        try {
            String encodePassword = passwordEncoder.encode(defaultPassword);
            log.info("============账号:{},密码:{}============", account, encodePassword);
            user = new User(defaultAccount, encodePassword, AuthorityUtils.createAuthorityList("ROLE_USER"));
        }catch (Exception ex){
            throw new RuntimeException("用户不存在");
        }
        return user;
    }
}
